﻿Imports System.Data.OleDb

Public Class QuestionGateway
    Inherits DataGateway

    Protected Overrides ReadOnly Property FindAllQuery As String
        Get
            Return "SELECT * FROM QuestionListView"
        End Get
    End Property

    Protected Overrides ReadOnly Property DeleteQuery As String
        Get
            Return "DELETE FROM Question"
        End Get
    End Property

    Protected Overrides ReadOnly Property SiteUserQuery() As String
        Get
            Return "SELECT SiteUser.* " &
                   "FROM Question LEFT JOIN SiteUser " &
                   "ON Question.UserID=SiteUser.ID " &
                   "WHERE Question.ID=@ID"
        End Get
    End Property

    Public Function FindByTag(ByVal tag As String) As DataTable
        Dim sqlQuery As String = "SELECT DISTINCT QuestionListView.* FROM QuestionListView " &
                                 "INNER JOIN QuestionTagsView ON QuestionListView.ID = QuestionTagsView.ID " &
                                 "WHERE QuestionTagsView.Title LIKE '%' + @TagTitle + '%'"
        Dim queryParams As New OrderedDictionary()
        queryParams.Add("@TagTitle", tag)
        Return QueryTable(sqlQuery, queryParams)
    End Function

    Public Function Insert(ByVal title As String, ByVal description As String, ByVal userID As ULong) As ULong
        Dim newID As ULong
        Dim sqlQuery As String = "INSERT INTO Question (Title, Description, UserID) VALUES (@Title, @Description, @UserID)"
        Using connection As New OleDbConnection(ConnectionString)
            Using command As New OleDbCommand(sqlQuery, connection)
                command.CommandType = CommandType.Text
                command.Parameters.AddWithValue("@Title", title)
                command.Parameters.AddWithValue("@Description", description)
                command.Parameters.AddWithValue("@UserID", userID)
                connection.Open()
                command.ExecuteNonQuery()
                newID = GetLastInsertID(command)
            End Using
        End Using

        Return newID
    End Function

    Public Sub Update(ByVal questionID As ULong, ByVal title As String, ByVal description As String)
        Dim sqlQuery As String = "UPDATE Question SET Title=@Title, Description=@Description WHERE ID=@QuestionID"
        Using connection As New OleDbConnection(ConnectionString)
            Using command As New OleDbCommand(sqlQuery, connection)
                command.CommandType = CommandType.Text
                command.Parameters.AddWithValue("@Title", title)
                command.Parameters.AddWithValue("@Description", description)
                command.Parameters.AddWithValue("@QuestionID", questionID)
                connection.Open()
                command.ExecuteNonQuery()
            End Using
        End Using
    End Sub
End Class
